package com.zysf.library_boot.util;

import cn.hutool.core.util.IdUtil;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDate;

public class UploadFile {
    public static String fileUrl(MultipartFile file){
        if (file.isEmpty()){
            return "文件为空";
        }else {
            int year = LocalDate.now().getYear();
            int month = LocalDate.now().getMonthValue();
            String localPath = "D:\\code\\library_boot\\src\\main\\resources\\static\\pic\\";
            String tarDir = year+"_"+month;
            File up_dir = new File(localPath+tarDir);
            if (!up_dir.exists()){
                up_dir.mkdirs();
            }
            String originalFilename = file.getOriginalFilename();
            //解决文件名重复问题
            //获取文件后缀
            String ext = originalFilename.substring(originalFilename.lastIndexOf("."));
            //拼接文件名
            String newFileName = IdUtil.simpleUUID()+ext;
            //组合文件存放的完整路径

            //保存文件
            try {
                file.transferTo(new File(up_dir, newFileName));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            String accessPath = "http://localhost:8888/upLoadImg/"+tarDir+"/"+newFileName;
            return accessPath;
        }
    }
}
